I like to namespace my code with object literals to contain all my functions and classes. It keeps things organized, decreases global space pollution from additional functions, and prevents conflicts with third-party scripts. It\’s very easy to extend too.
Create the Namespaced Object
I usually start out by checking whether the namespaced object literal is already existing, and if it\’s not, then create one. You can use the name of the website, or your initials, whatever works. I\’m going to use my initials and \”CORE\”.
if(!GTC_CORE){
var GTC_CORE = {};
}
Extend your Namespace
Like I said, I like to use dot notation. It\’s just my preference.
GTC_CORE.printHello = function(){
alert(\'Hello!\');
}
GTC_CORE.printWelcome = function(){
alert(\'Welcome!\');
}
Namespace in Action
So here we have a GTC_CORE namespaced object. Now let\’s say we want to run the printHello function. You just run it like how you do any other function you\’ve written.
GTC_CORE.printHello(); // Alert appears printing \'Hello!\'
GTC_CORE.printWelcome(); // Alert appears printing \'Welcome!\'
Alternative to Dot Notation: Start with the Object Literal
There are other ways to create a namespace. Here we\’re just plugging in the functions into the object literal GTC_CORE. Notice that every addition requires a comma, except the last one. I\’ll also throw in a couple examples for variables and nesting object literals inside.
var GTC_CORE = {
// printHello function
\'printHello\': function(){
alert(\'Hello!\');
},
//printWelcome function
\'printWelcome\': function(){
alert(\'Welcome!\');
},
//the value of \'name\' is Garrick, a string
\'name\': \'Garrick\',
//the value of \'num\' is 12, an int
\'num\': 12,
//nested object literal
\'nested\': {
\'val1\': 1,
\'val2\': 2
}
}
GTC_CORE.printHello(); //Alerts with \"Hello!\"
GTC_CORE.printWelcome(); //Alerts with \"Welcome!\"
GTC_CORE.name; //returns \'Garrick\'
GTC_CORE.num; //returns 10
GTC_CORE.nested; //returns object literal
Good